﻿package net.wangit.view.enumeration;

import net.wangit.MapList;
import net.wangit.context.ActionContext;
import net.wangit.context.LocalContext;
import net.wangit.framework.util.DataPrivilegeUtil;
import net.wangit.framework.util.UnitDataUtil;
import net.wangit.jdbc.DB;
import net.wangit.jdbc.DBFactory;
import net.wangit.support.SqlProvider;
import net.wangit.util.ClassUtil;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class EnumerationDataUtil {

	private static final Log log = LogFactory
			.getLog(net.wangit.view.enumeration.EnumerationDataUtil.class);

	public EnumerationDataUtil() {
	}

	public static MapList createEnumeration(String domain,
			EnumerationConfig config) {
		DB db;
		String sql;
		ActionContext ac = LocalContext.getLocalContext().getActionContext();
		try {
			db = DBFactory.getDB(config.getDatasource());
			sql = getOriginalSql(ac, config);
			if (config.hasDataPrivilege())
				sql = DataPrivilegeUtil.getEnumerationSql(config.getDomain(),
						config.getId(), sql);
			sql = UnitDataUtil.resolveSQL(ac, sql);
			return db.query(sql);
		} catch (Exception e) {
			log.error((new StringBuilder("create Enumeration failed:")).append(
					e).toString());
			return null;
		}
	}

	private static String getOriginalSql(ActionContext ac,
			EnumerationConfig config) throws Exception {
		String sql = config.getDataExpression();
		if (config.getDataMode() == 0)
			try {
				SqlProvider provider = (SqlProvider) ClassUtil.loadClass(sql)
						.newInstance();
				sql = provider.getSql(ac);
			} catch (Exception e) {
				log
						.error((new StringBuilder(
								"Enumeration SqlProvider error : ")).append(
								config.getDomain()).append("/").append(
								config.getId()).append("(").append(sql).append(
								")").toString());
				throw e;
			}
		return sql;
	}

}
